package com.example.widgetcase.slice.viewpager;

import com.example.widgetcase.ResourceTable;
import ohos.agp.components.*;
import ohos.app.Context;
import ohos.utils.LruBuffer;

import java.util.List;

public class ViewPagerAdapter extends PageSliderProvider {

    private Context mContext;
    private List<Integer> images;
    private LruBuffer mCachePagerItem = new LruBuffer<Integer, Image>(5);

    public ViewPagerAdapter(Context context, List<Integer> images) {
        this.mContext = context;
        this.images = images;
    }

    @Override
    public int getCount() {
        return images.size();
    }

    @Override
    public Object createPageInContainer(ComponentContainer componentContainer, int i) {
        Object obj = mCachePagerItem.get(i);
        if (obj == null) {
            LayoutScatter scatter = LayoutScatter.getInstance(mContext);
            Image image = (Image) scatter.parse(ResourceTable.Layout_viewpager_itemview, null, false);
            image.setTag(i);
            mCachePagerItem.put(i, image);
            obj = image;

            image.setScale(0.9f, 0.9f);

            image.setPixelMap(images.get(i));
            componentContainer.addComponent(image);
        }
        return obj;
    }

    @Override
    public void destroyPageFromContainer(ComponentContainer componentContainer, int i, Object o) {
        componentContainer.removeComponent((Image) o);
    }

    @Override
    public boolean isPageMatchToObject(Component component, Object o) {
        return component == o;
    }

}
